<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChLockCustomerCodeRecord;
use Mine\Abstracts\AbstractMapper;

class ChLockCustomerCodeRecordMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChLockCustomerCodeRecord::class;
    }

    public function getCodeStatisticsByUid(array $data)
    {
        $uid = $data['uid'];
        // 处理code_ids参数
        $codeIds = (array)($data['code_ids'] ?? []);
        $codeIds = array_filter(array_map('intval', $codeIds));

        // 构建基础查询
        $query = $this->model::query()->where('uid', $uid);

        // 执行统计查询
        return $query
            ->selectRaw('
            code_id,
            COUNT(*) as total_count,
            COUNT(CASE WHEN is_new_contact = 0 THEN 1 END) as old_contact_count,
            COUNT(CASE WHEN is_add_friend = 1 THEN 1 END) as added_friend_count
        ')
            ->when(!empty($codeIds), function ($q) use ($codeIds) {
                $q->whereIn('code_id', $codeIds);
            })
            ->groupBy('code_id')
            ->get()
            ->keyBy('code_id');
    }

    public function findByUidAndUserId($uid, $userId)
    {
        return $this->model::query()
            ->where('uid', $uid)
            ->where('user_id', $userId)
            ->orderByDesc('created_at')
            ->first();
    }
}